package cn.school.student.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.school.classManage.dao.SchoolClassDao;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.api.CommonPage;
import cn.school.common.utils.SysUserUtils;
import cn.school.student.dao.*;
import cn.school.student.entity.*;
import cn.school.student.entity.vo.ExamPublishParam;
import cn.school.student.entity.vo.ExamPublishVo;
import cn.school.student.entity.vo.ExamTestPassRatioVo;
import cn.school.student.service.ExamPublishService;
import cn.school.sys.entity.SysUser;
import cn.school.sys.entity.SysUserRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExamPublishServiceImpl extends ServiceImpl<ExamPublishDao,ExamPublish> implements ExamPublishService {
	
	@Autowired
	private ExamPublishDao examPublishDao;
	@Resource
	private StudentInfoDao studentInfoDao;
	@Resource
	private TExamPerformanceDao tExamPerformanceDao;
	@Resource
	private TExamCorrelationDao tExamCorrelationDao;
	@Resource
	private ExamPublishStudentDao examPublishStudentDao;
	
	@Autowired
	private TStudentExamPerformanceDao studentExamPerformanceDao;
	
	@Autowired
	private TExamPublishPaperDao tExamPublishPaperDao;
	
	@Autowired
	private SchoolClassDao schoolClassDao;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int insert(ExamPublish examPublish) {
		String username = SysUserUtils.getSysUser().getUsername();
		//发布表添加记录
		int num = examPublishDao.insert(examPublish);
		//查询班级学生
		LambdaQueryWrapper<StudentInfo> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(StudentInfo::getClassId, examPublish.getClassId());
		wrapper.eq(StudentInfo::getStatus, 1);
		List<StudentInfo> studentInfoList = studentInfoDao.selectList(wrapper);
		ExamPublishStudent psInfo = null;
		for (StudentInfo sinfo : studentInfoList) {
			psInfo = new ExamPublishStudent();
			psInfo.setCreateBy(username);
			psInfo.setCreateTime(new Date());
			psInfo.setTestPaperId(Long.valueOf(examPublish.getTestPaperId()));
			psInfo.setStudentId(sinfo.getId());
			psInfo.setPublishId(examPublish.getId());
			psInfo.setIsSubmit(0L);
			psInfo.setClassId(sinfo.getClassId());
			psInfo.setPubilishType(examPublish.getPubilishType());
			examPublishStudentDao.insert(psInfo);
		}
		//查询试卷题目
		LambdaQueryWrapper<TExamCorrelation> wrapperCorrelation = new LambdaQueryWrapper<>();
		wrapperCorrelation.eq(TExamCorrelation::getTestpaperId, examPublish.getTestPaperId());
		List<TExamCorrelation> testpaperLuist = tExamCorrelationDao.selectList(wrapperCorrelation);
		List<TExamPerformance> perforList = null;
		TExamPerformance examPerformance = null;
		for (StudentInfo sinfo : studentInfoList) {
			perforList = new ArrayList<>();
			for (TExamCorrelation corr : testpaperLuist) {
				examPerformance = new TExamPerformance();
				examPerformance.setCreateBy(username);
				examPerformance.setCreateTime(new Date());
				examPerformance.setTestpaperId(examPublish.getTestPaperId());
				examPerformance.setStudentId(sinfo.getId());
				examPerformance.setPublishId(examPublish.getId());
				examPerformance.setQuestionsId(corr.getQuestionsId());
				perforList.add(examPerformance);
			}
			//给每个学生添加考卷试题
			tExamPerformanceDao.insertBatch(perforList);
		}
		return num;
	}
	
	@Override
	public CommonPage<ExamPublishVo> queryList(ExamPublishParam examPublishParam) {
		CommonPage<ExamPublishVo> page = new CommonPage<>();
		page.setPageSize(examPublishParam.getPageSize());
		examPublishParam.setPageNum((examPublishParam.getPageNum()-1)*examPublishParam.getPageSize());
		page.setPageNum((examPublishParam.getPageNum()-1)*examPublishParam.getPageSize());
		
		SysUser user = SysUserUtils.getSysUser();
		List<SysUserRole> roleList = user.getRoleInfoList();
		boolean isBanzhuren = roleList.stream().anyMatch(m->m.getRoleName().equals("班主任"));
		if(isBanzhuren){
			examPublishParam.setCreateBy(user.getUsername());
		}
		// 查询登录用户的班级
		List<SchoolClassVO> vo = schoolClassDao.findClassName(String.valueOf(SysUserUtils.getSysUser().getId()));
		List<String> list = new ArrayList<>();
		for (SchoolClassVO classVO:vo){
			
			list.add(classVO.getClassName());
			
		}
		if(list.size()!=0){
			examPublishParam.setClassNameList(list);
		}
		List<ExamPublishVo> examPublishVOS = examPublishDao.queryList(examPublishParam);
		page.setList(examPublishVOS);
		page.setTotal((long) this.examPublishDao.count(examPublishParam));
		
		return page;
		
	}
	
	@Override
	public List<ExamPublishVo> selectByquesitonsName(String studentId, String publishId) {
		return this.examPublishDao.selectByquesitonsName(studentId, publishId);
	}
	
	@Override
	public Long count(ExamPublishParam examPublishParam) {
		return (long) this.examPublishDao.count(examPublishParam);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int cancelPublish(String publishId) {
		//删除发布学生表数据
		LambdaQueryWrapper<ExamPublishStudent> wrapperPublishStudent = new LambdaQueryWrapper<>();
		wrapperPublishStudent.eq(ExamPublishStudent::getPublishId,publishId);
		examPublishStudentDao.delete(wrapperPublishStudent);
		//删除学生答题表数据
		LambdaQueryWrapper<TExamPerformance> wrapperPerformance = new LambdaQueryWrapper<>();
		wrapperPerformance.eq(TExamPerformance::getPublishId,publishId);
		tExamPerformanceDao.delete(wrapperPerformance);
		//删除发布表数据
		return examPublishDao.deleteById(publishId);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int correctExamByStudent(List<TExamPerformance> TExamCorrelation) {
		String studentId="";
		String publishId="";
		for (TExamPerformance tExamPerformance : TExamCorrelation) {
			//更新答题分数
			BigDecimal scores = new BigDecimal(tExamPerformance.getGradesScores());
			if(scores.compareTo(BigDecimal.ZERO)>0){
				tExamPerformance.setIsRight("1");
			}
			tExamPerformanceDao.updateById(tExamPerformance);
			studentId = String.valueOf(tExamPerformance.getStudentId());
			publishId = String.valueOf(tExamPerformance.getPublishId());
		}
		//查询学生答题的总分
		String sum = tExamPerformanceDao.queryExamScoreSum(studentId, publishId);
		//更新批改情况
		LambdaQueryWrapper<ExamPublishStudent> wrapperPublishStudent = new LambdaQueryWrapper<>();
		wrapperPublishStudent.eq(ExamPublishStudent::getPublishId,Long.valueOf(publishId));
		wrapperPublishStudent.eq(ExamPublishStudent::getStudentId,Long.valueOf(studentId));
		ExamPublishStudent examPublishStudent = new ExamPublishStudent();
		examPublishStudent.setCorrectStatus("1");//已批准
		examPublishStudent.setExamScore(new BigDecimal(sum));
		
		
		return examPublishStudentDao.update(examPublishStudent,wrapperPublishStudent);
	}
	
	@Override
	public List<ExamTestPassRatioVo> getQuestionPassRatioByPublishPaper(Long publishId) {
		List<ExamTestPassRatioVo> results = new ArrayList<>();
		// 查询出试卷和每道题目的基本信息
		LambdaQueryWrapper<TExamPublishPaper> publishQueryWrapper = new LambdaQueryWrapper<>();
		publishQueryWrapper.eq(TExamPublishPaper::getPublishId, publishId);
		List<TExamPublishPaper> examPublishPapers = tExamPublishPaperDao.selectList(publishQueryWrapper);
		if (CollectionUtil.isEmpty(examPublishPapers)) {
			return Collections.emptyList();
		}
		
		// 查询出考试这套试卷的学生名单
		LambdaQueryWrapper<TStudentExamPerformance> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(TStudentExamPerformance::getPublishId, publishId);
		lambdaQueryWrapper.eq(TStudentExamPerformance::getIsSubmit, "1");
		List<TStudentExamPerformance> studentExamPerformances = studentExamPerformanceDao.selectList(lambdaQueryWrapper);
		
		Map<Long, List<TStudentExamPerformance>> listMap = studentExamPerformances.stream().collect(Collectors.groupingBy(TStudentExamPerformance::getQuestionsId));
		
		// 根据学生的答题情况来匹配每道题目的 通过的学生名单 考试情况表
		for (TExamPublishPaper examPublishPaper : examPublishPapers) {
			ExamTestPassRatioVo ratioVo = new ExamTestPassRatioVo();
			ratioVo.setPublishId(examPublishPaper.getPublishId());
			ratioVo.setQuestionsId(examPublishPaper.getQuestionsId());
			ratioVo.setQuestionsName(examPublishPaper.getQuestionsName());
			ratioVo.setQuestionType(examPublishPaper.getQuestionsType());
			ratioVo.setUnit(examPublishPaper.getUnit());
			ratioVo.setOptions(examPublishPaper.getOptions());
			List<TStudentExamPerformance> performances = listMap.get(examPublishPaper.getQuestionsId());
			if (CollectionUtil.isEmpty(performances)) {
				ratioVo.setPassStudents(Collections.emptyList());
				ratioVo.setSubmitStudents(Collections.emptyList());
				results.add(ratioVo);
				continue;
			}
			ratioVo.setSubmitStudents(performances);
			List<TStudentExamPerformance> rightStudent = performances.stream().filter(tStudentExamPerformance -> Objects.equals(tStudentExamPerformance.getIsRight(), "1")).collect(Collectors.toList());
			ratioVo.setPassStudents(rightStudent);
			
			List<TStudentExamPerformance> wrongStudent = performances.stream().filter(tStudentExamPerformance -> Objects.equals(tStudentExamPerformance.getIsRight(), "0")).collect(Collectors.toList());
			ratioVo.setWrongStudents(wrongStudent);
			results.add(ratioVo);
		}
		
		return results;
	}
}
